import utilService from '../service/utilService.js'
import userService from '../service/userService.js'
import constant from '../util/constant'

const $registerForm = $('#JS-register-form');
const $register = $('#JS-register');
const $verifyCode = $('#JS-verify-code');

let user = {};

// trackId
let tid = utilService.getUrlParams().trackId || utilService.getUrlParams().trackid;
utilService.saveCookie('tid', tid);

// utmc
let utmc = utilService.getUrlParams().utm_content || '';
utmc && utilService.saveCookie('utmc', utmc);

// 发送验证码
$verifyCode.click(function () {
    user.key = utilService.getValue($registerForm, 'key');
    user.ivc = utilService.getValue($registerForm, 'ivc');
    user.type = constant.SendCode_Register;
    let result = utilService.validate(['key', 'ivc'], user);
    if (result.status) {
        userService.sendCode(user).then(data => {
            utilService.clearError($registerForm)
            utilService.countDown($verifyCode);
        }, err => {
            if (err.resultMsg.indexOf('注册') != -1) {
                err.name = 'key';
            } else if (err.resultMsg.indexOf('一分钟') != -1) {
                err.name = 'verifyCode';
            } else {
                err.name = 'ivc';
            }
            utilService.setError($registerForm, err);
        })
    } else {
        utilService.setError($registerForm, result);
    }
});

// 注册
$register.click(function () {
    user.verifyCode = utilService.getValue($registerForm, 'verifyCode');
    user.telephone = user.key = user.userName = utilService.getValue($registerForm, 'key');
    user.ivc = utilService.getValue($registerForm, 'ivc');
    user.pwd = user.pwd2 = utilService.getValue($registerForm, 'pwd');
    user.regSource = 1;
    user.trackId = tid;
    let result = utilService.validate(['key', 'ivc', 'verifyCode', 'pwd'], user);
    if (result.status) {
        userService.regsave(user).then(data => {
            utilService.toHref(constant.Pc_index_url);
        }, err => {
            if (err.resultMsg.indexOf('注册') != -1) {
                err.name = 'key';
            } else if (err.resultMsg.indexOf('验证码') != -1) {
                err.name = 'verifyCode';
            } else {
                err.name = 'pwd';
            }
            utilService.setError($registerForm, err);
        })
    } else {
        utilService.setError($registerForm, result);
    }
});